package de.baumann.browser.fragments;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import de.baumann.browser.R;
import de.baumann.browser.activitys.MainActivity;
import de.baumann.browser.activitys.WebSiteActivity;
import de.baumann.browser.activitys.oc.OcWalletActivity;
import de.baumann.browser.adapter.HomeWebsiteAdapter;
import de.baumann.browser.adapter.PagerAdapter;
import de.baumann.browser.api.net.vo.NewsColumn;
import de.baumann.browser.base.BaseOdinFragment;
import de.baumann.browser.db.ETHWallet;
import de.baumann.browser.iview.IHomeView;
import de.baumann.browser.present.HomePresenter;
import de.baumann.browser.units.LocationUnit;
import de.baumann.browser.utils.Constants;
import de.baumann.browser.utils.web3j.WalletDaoUtils;
import de.baumann.browser.views.behavior.UCViewHeaderBehavior;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class IndexFragment extends BaseOdinFragment<IHomeView, HomePresenter> implements IHomeView, View.OnClickListener {
    @SuppressLint("StaticFieldLeak")
    private static IndexFragment instance = null;

    public IndexFragment() {
    }

    public static IndexFragment getInstance() {
        synchronized (IndexFragment.class) {
            if (instance == null) {
                instance = new IndexFragment();
            }
        }
        return instance;
    }

    private RecyclerView mRvWebsite;
    private ViewPager mNewsPager;
    private TabLayout mNewsTab;
    private TextView mTvCity;
    private TextView mTvTmp;
    private TextView mTvWeatherStatus;
    private UCViewHeaderBehavior mUCViewHeaderBehavior;

    @Override
    public int getLayout() {
        return R.layout.fragment_index;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initView(@NotNull View view) {

        mUCViewHeaderBehavior = (UCViewHeaderBehavior) ((CoordinatorLayout.LayoutParams) view.findViewById(R.id.news_view_header_layout).getLayoutParams()).getBehavior();
        mTvTmp = view.findViewById(R.id.indexTvTmp);
        mTvCity = view.findViewById(R.id.tvCity);
        mTvWeatherStatus = view.findViewById(R.id.tvWeatherStatus);

        view.findViewById(R.id.indexSearchbox).setOnClickListener(this);
        view.findViewById(R.id.llTopSearchBox).setOnClickListener(this);
        view.findViewById(R.id.iv1).setOnClickListener(this);
        view.findViewById(R.id.iv2).setOnClickListener(this);
        view.findViewById(R.id.iv3).setOnClickListener(this);

        mNewsPager = view.findViewById(R.id.newsViewContentLayout);
        mNewsTab = view.findViewById(R.id.newsViewTabLayout);
        mRvWebsite = view.findViewById(R.id.indexRvWebsite);
        mRvWebsite.setLayoutManager(new GridLayoutManager(mContext, 6));
        HomeWebsiteAdapter homeWebsiteAdapter = new HomeWebsiteAdapter(mContext, Constants.WEBSITES);
        mRvWebsite.setAdapter(homeWebsiteAdapter);
        homeWebsiteAdapter.setWebsiteClickListener(url -> WebSiteActivity.Companion.startWebSiteActivity(mContext, url));
        IndexFragmentPermissionsDispatcher.startLocaionWithPermissionCheck(this);

//        view.findViewById(R.id.ivWalletIn).setOnClickListener(view1 -> {
//
//            List<ETHWallet> ethWallet = WalletDaoUtils.loadAll();
////            if (ethWallet == null || ethWallet.size() <= 0) {
//////                OcWalletActivity.Companion.startOcWalletActivity(mContext);
////            } else {
//////                OcWalletDetailActivity.Companion.startOcWalletDetailActivity(mContext);
//////                OCBActivity.Companion.startOCBActivity(mContext,null);
////            }
//
//        });

//        ImageView indexRedPack = view.findViewById(R.id.indexRedPack);

//        indexRedPack.setOnClickListener(view12 -> RedPacketActivity.Companion.startRedPacketActivity(mContext));

//        ((MainActivity) getActivity()).setDispatchTouchListener(ev -> {
//            if (ev.getAction() == MotionEvent.ACTION_MOVE) {
//                indexRedPack.setVisibility(View.GONE);
//            }else{
//                indexRedPack.setVisibility(View.VISIBLE);
//            }
//        });
    }


    @Override
    public void initData() {
        getPresenter().getNewColumns();
    }

    @NeedsPermission({Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION})
    public void startLocaion() {
        LocationUnit.initLocation(mContext, aMapLocation -> {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                LocationUnit.stopLocation();
                getPresenter().getWeather(aMapLocation.getCity());
            }
        });
        LocationUnit.startLocation();
    }

    @Nullable
    @Override
    public HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Nullable
    @Override
    public IHomeView createView() {
        return this;
    }

    @Override
    public void setCity(@NotNull String city) {
        mTvCity.setText(city);
    }

    @Override
    public void setTmp(@NotNull String tmp) {
        mTvTmp.setText(String.format("%s ℃", tmp));
    }

    @Override
    public void setPm25(@NotNull String pm25) {

    }

    @Override
    public void setQlty(@NotNull String qlty) {

    }

    @Override
    public void setCondTxt(@NotNull String condTxt) {
        mTvWeatherStatus.setText(condTxt);
    }

    @Override
    public void setColumns(@NotNull ArrayList<NewsColumn> columns) {
        String[] titles = new String[columns.size()];
        List<Fragment> fragments = new ArrayList<>(columns.size());
        for (int i = 0; i < columns.size(); i++) {
            titles[i] = columns.get(i).getColumnTitle();
            NewsListFragment fragment = new NewsListFragment();
            Bundle bundle = new Bundle();
            bundle.putString("columnId", columns.get(i).getColumnId());
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }
        PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), fragments, titles);
        mNewsPager.setAdapter(pagerAdapter);
        mNewsTab.setupWithViewPager(mNewsPager);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.indexSearchbox:
            case R.id.llTopSearchBox:
                ((MainActivity) getActivity()).showSearchView();
                break;
            case R.id.iv1:
                WebSiteActivity.Companion.startWebSiteActivity(mContext, Constants.IV1);
//                ReadArticleActivity.Companion.startReadArticleActivityWithTitle(mContext, Constants.IV1, getString(R.string.Around_ODIN));
                break;
            case R.id.iv2:
//                ReadArticleActivity.Companion.startReadArticleActivityWithTitle(mContext, Constants.IV3, getString(R.string.information_ODIN));
                WebSiteActivity.Companion.startWebSiteActivity(mContext, Constants.IV3);
                break;
            case R.id.iv3:
                WebSiteActivity.Companion.startWebSiteActivity(mContext, Constants.IV2);
//                ReadArticleActivity.Companion.startReadArticleActivityWithTitle(mContext, Constants.IV2, getString(R.string.help_ODIN));
                break;
            default:
        }
    }


    public boolean isClosed() {
        return mUCViewHeaderBehavior.isClosed();
    }

    public void openPager() {
        mUCViewHeaderBehavior.openPager();
    }

    @Override
    public boolean showBindEth() {
        return false;
    }


}
